package com.yfh.sharding.datasource.config.sharding;

import com.yfh.sharding.datasource.constants.DatasourceType;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;

import java.util.Collection;
import java.util.HashSet;

/**
 * @author : DaiGD
 * @createtime :  2020年06月13日 16:42
 * @description : 数据库分片策略
 */
@Slf4j
public class MyDatasourceRoutingAlgorithm implements HintShardingAlgorithm<String> {


    /**
     * 用户数据源
     */
    private static final String DS_USER = "ds1";

    /**
     * 老师数据源
     */
    private static final String DS_TEACHER = "ds2";

    /**
     * 班级数据源
     */
    private static final String DS_CLASS = "ds3";

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<String> shardingValue) {
        Collection<String> result = new HashSet<>();
        for (String value : shardingValue.getValues()) {
            if (DatasourceType.DATASOURCE_USER.equals(value)) {
                if (availableTargetNames.contains(DS_USER)) {
                    result.add(DS_USER);
                }
            } else if(DatasourceType.DATASOURCE_TEACHER.equals(value)) {
                if (availableTargetNames.contains(DS_TEACHER)) {
                    result.add(DS_TEACHER);
                }
            } else {
                if (availableTargetNames.contains(DS_CLASS)) {
                    result.add(DS_CLASS);
                }
            }
        }
        log.info("availableTargetNames:{},shardingValue:{},返回的数据源:{}",
                new Object[]{availableTargetNames, shardingValue, result});

        return result;
    }
}
